package top.lishuoboy.hibernate.validator.config.advice;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import top.lishuoboy.hibernate.validator.dto.Result;


/**
 * <h1>控制器统一响应体包装</h1>
 * <p>
 * 2024-10-25
 * <p>
 * 方法没有注解 @NotResult
 * 方法返回类型不是Result
 * 方法返回类型不是String
 *
 * @author lishuoboy
 */
@RestControllerAdvice(basePackages = "top.lishuoboy.hibernate.validator.controller")
public class ResponseBodyControllerAdvice implements ResponseBodyAdvice<Object> {

    /** 支持类型 */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return !(methodParameter.hasMethodAnnotation(NotResult.class)                       // 方法没有注解 @NotResult
            || methodParameter.getParameterType().isAssignableFrom(Result.class)            // 方法返回类型不是Result
            || methodParameter.getParameterType().isAssignableFrom(String.class));          // 方法返回类型不是String
    }

    /** 返回响应体之前包装处理 */
    @Override
    public Result<Object> beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        return Result.success(o);
    }
}